package org.jeecg.modules.flow.callback.outbound.order;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.basic.plant.entity.WmsSapWarehouseMap;
import org.jeecg.modules.basic.plant.mapper.WmsSapWarehouseMapMapper;
import org.jeecg.modules.basic.saplocation.entity.WmsSapLocation;
import org.jeecg.modules.basic.saplocation.service.IWmsSapLocationService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseMapper;
import org.jeecg.modules.business.doc.outbound.entity.WmsOutReceiptMaterial;
import org.jeecg.modules.business.doc.outbound.service.IWmsOutReceiptMaterialService;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.dock.entity.dto.request.InventoryAdjustRequestDTO;
import org.jeecg.modules.dock.entity.dto.response.InventoryUpdateResponseDTO;
import org.jeecg.modules.dock.service.SapDockingRepeaterService;
import org.jeecg.modules.flow.callback.enums.SimpleDocumentTypeEnum;
import org.jeecg.modules.flow.callback.enums.TransferStatusEnum;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 盘亏单过账sap回调bean
 *
 * @author lumingyi
 * @version 1.0.0
 * @since 2024-01-17
 */
@RequiredArgsConstructor
@Component
public class C33PKDPassSAPBean<T> extends BaseCustomBeanRun<T> {

    private final SapDockingRepeaterService sapDockingRepeaterService;
    private final WmsSapWarehouseMapMapper sapWarehouseMapMapper;
    private final WmsBasicWarehouseMapper warehouseMapper;
    private final IWmsSapLocationService sapLocationService;
    private final IWmsOutReceiptMaterialService outReceiptMaterialService;
    private final IWmsOutReceiptTaskService outReceiptTaskService;

    /**
     * 业务逻辑 盘亏单出库单保存并提交
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void actureRun() {

        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        String id = baseFlowDto.getInfoId();
        List<WmsOutReceiptMaterial> wmsOutReceiptMaterials = outReceiptMaterialService.selectByMainId(id);
        // 过账sap
        List<InventoryAdjustRequestDTO> list = new ArrayList<>();
        for (WmsOutReceiptMaterial material : wmsOutReceiptMaterials) {
            InventoryAdjustRequestDTO dto = new InventoryAdjustRequestDTO();
            dto.setMaterialCode(material.getMaterialCode());
            WmsSapWarehouseMap one = sapWarehouseMapMapper.selectOne(new LambdaQueryWrapper<WmsSapWarehouseMap>()
                    .eq(WmsSapWarehouseMap::getWmsBasicWarehouseId, material.getWmsBasicWarehouseId())
                    .last("limit 1"));
            if (one == null) {
                WmsBasicWarehouse warehouse = warehouseMapper.selectById(material.getWmsBasicWarehouseId());
                baseFlowDto.setResult("过账失败，仓库【" + warehouse.getName() + "】没有配置对应的sap库位");
                //更新过账状态 过账失败
                outReceiptTaskService.updateTransferStatus(SimpleDocumentTypeEnum.OUT_RECEIPT,null, id, TransferStatusEnum.TRANSFER_FAIL);
            }
            dto.setLocation(one.getSapLocation());
            WmsSapLocation sapLocation = sapLocationService.getOne(new LambdaQueryWrapper<WmsSapLocation>()
                    .eq(WmsSapLocation::getCode, one.getSapLocation())
                    .last("limit 1"));
            if (sapLocation == null) {
                WmsBasicWarehouse warehouse = warehouseMapper.selectById(material.getWmsBasicWarehouseId());
                baseFlowDto.setResult("过账失败，仓库【" + warehouse.getName() + "】没有配置对应的工厂");
                //更新过账状态 过账失败
                outReceiptTaskService.updateTransferStatus(SimpleDocumentTypeEnum.OUT_RECEIPT,null, id, TransferStatusEnum.TRANSFER_FAIL);
            }
            dto.setFactory(sapLocation.getFactory());
            dto.setSaleOrderCode(material.getSaleOrderNumber());
            dto.setSaleOrderCodeLine(material.getSaleOrderLineNumber());
            dto.setAdjustNumber(new BigDecimal("0").subtract(material.getOutboundQuantity()));  // 盘亏是负数
            list.add(dto);
        }
        List<InventoryUpdateResponseDTO> dtos = new ArrayList<>();
        try {
            dtos = sapDockingRepeaterService.inventoryCountAdjustment(list);
        } catch (Exception e) {
            baseFlowDto.setResult("盘亏单过账sap失败: " + e.getMessage());
            //更新过账状态 过账失败
            outReceiptTaskService.updateTransferStatus(SimpleDocumentTypeEnum.OUT_RECEIPT,null, id, TransferStatusEnum.TRANSFER_FAIL);
        }
        if (CollectionUtil.isNotEmpty(dtos)) {
            InventoryUpdateResponseDTO res = dtos.get(0);
            if ("E".equals(res.getResult())) {
                baseFlowDto.setResult("盘亏单过账sap失败: " + res.getMessage());
                //更新过账状态 过账失败
                outReceiptTaskService.updateTransferStatus(SimpleDocumentTypeEnum.OUT_RECEIPT,null, id, TransferStatusEnum.TRANSFER_FAIL);
            }
        }
        // 当前前端调用业务需要你返回的
        baseFlowDto.setResult(Result.OK());
    }

}
